package rest

import (
	"crypto/tls"
	"encoding/json"
	"gitee.com/cooge/impush/config"
	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	"gitee.com/cooge/impush/user"
	"log"
	"net/http"
	"strconv"
	"strings"
)

func root(w http.ResponseWriter, re *http.Request) {
	core.AddInfo("USER_NUM", user.AllLen())
	mssg, err := json.Marshal(core.GetInfo())
	if err == nil {
		w.Write(mssg)
	}
}

func sendMsg(w http.ResponseWriter, re *http.Request) {
	id := re.FormValue("id")
	msg := re.FormValue("msg")
	if len(id) == 0 || len(msg) == 0 {
		w.WriteHeader(404)
		w.Write([]byte(`{"code":404,"msg":"id is blank"}`))
	} else {
		ids:=strings.Split(id,",")
		u := make([]*SendMsgStatus, 0)
		mm := message.GetSystemMessage(id, msg)
		for _,k:=range ids{
			if len(k)>0{
				_, err := core.SendMessage(k, mm)
				if err != nil {
					u = append(u, &SendMsgStatus{k,message.FULL_NOUSER})
				} else {
					u = append(u, &SendMsgStatus{k,message.FULL_SUCCESS})
				}
			}
		}
		mssg, err := json.Marshal(u)
		if err == nil {
			w.Write(mssg)
		}else{
			w.WriteHeader(500)
			w.Write([]byte(`{"code":500,"msg":"`+err.Error()+`"}`))
		}
	}
}

func SendMessage(w http.ResponseWriter, r *http.Request) {
	h := w.Header()
	h.Add("Access-Control-Allow-Origin", "*")
	to := r.FormValue(message.TO)
	from := r.FormValue(message.FROM)
	msg := r.FormValue(message.MESSAGE)
	if len(to) == 0 || len(from) == 0 || len(msg) == 0 {
		w.WriteHeader(404)
		w.Write([]byte(`{"code":404,"msg":"id is blank"}`))
	} else {
		u := make([]*SendMsgStatus, 0)
		mm := message.GetMessage(to, from, msg)
		_, err := core.SendMessage(to, mm)
		if err != nil {
			u = append(u, &SendMsgStatus{to,message.NO_USER})
		} else {
			u = append(u, &SendMsgStatus{to,message.SUCCESS})
		}
		mssg, err := json.Marshal(u)
		if err == nil {
			w.Write(mssg)
		}else{
			w.WriteHeader(500)
			w.Write([]byte(`{"code":500,"msg":"`+err.Error()+`"}`))
		}
	}
}
func queryuser(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	if len(id) == 0 {
		w.WriteHeader(404)
		w.Write([]byte(`{"code":404,"msg":"id is blank"}`))
	} else {
		us := core.GetUser(id)
		if us==nil{
			w.WriteHeader(404)
			w.Write([]byte(`{"code":404,"msg":"id is not found"}`))
		}else{
			u := make([]*UserLiteInfo, 0)
			for _, uc := range us.GetAllArray() {
				var ul UserLiteInfo
				ul.UserId = uc.GetUserId()
				ul.CreateTime = uc.GetCreateTime().Format(timeLayout)
				ul.IsLocal = uc.IsLocal()
				ul.Type = uc.GetType()
				ul.Address = uc.GetAddress()
				u = append(u, &ul)
			}
			mssg, err := json.Marshal(u)
			if err == nil {
				w.Write(mssg)
			}
		}
	}
}

func onlineuser(w http.ResponseWriter, r *http.Request) {
	start := r.FormValue("start")
	s, err := strconv.Atoi(start)
	if err != nil {
		s = 0
	}
	num := r.FormValue("num")
	n, err := strconv.Atoi(num)
	if err != nil {
		n = 0
	}
	sysinfo := make(map[string]interface{})
	sysinfo["num"] = user.AllLen()
	us := user.GetValueArray(s, n)
	u := make([]*UserInfo, 0)
	for _,v:=range us{
		var ui UserInfo
		ui.UserId = v.UserId
		ui.CreateTime=v.GetCreateTime().Format(timeLayout)
		ui.ConnNum = v.Len()
		ui.HasLocal = v.HasLocal()
		u = append(u, &ui)
	}
	sysinfo["list"] = u
	mssg, err := json.Marshal(sysinfo)
	if err == nil {
		w.Write(mssg)
	}
}

/**
  测试使用,不建议对外
*/

func deleteLocalUser(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	user.DeleteKey(id)
	w.Write([]byte(`{"code":200,"msg":"ok"}`))
}

func Start() {

	start()
}

func start() {



	http.HandleFunc("/", root)
	core.AddInfo("HTTP_PORT", config.HTTP_PORT)
	http.HandleFunc("/onlineuser", onlineuser)

	if config.LOG_OPEN {
		http.HandleFunc("/deleteLocalUser", deleteLocalUser)
	}

	http.HandleFunc("/sendmsg", sendMsg)
	http.HandleFunc("/queryuser", queryuser)

	server := &http.Server{
		Addr:         ":"+strconv.Itoa(config.HTTP_PORT),
		TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
		Handler:http.DefaultServeMux,
	}

	if config.HTTP_SSL{
		err :=	server.ListenAndServeTLS(config.CRT_NAME,config.KEY_NAME)
		if err != nil {
			log.Panic("启动失败", err)
		}
	}else{
		err :=server.ListenAndServe()
		if err != nil {
			log.Panic("启动失败", err)
		}
	}
}
